<template>
  <div class="appointment-form">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <button class="back-button" @click="goBack">
          <i class="icon">←</i>
        </button>
        <h1 class="page-title">预约咨询</h1>
        <div class="placeholder"></div>
      </div>
    </div>

    <div class="form-container">
      <form @submit.prevent="submitForm">
        <div class="form-section">
          <div class="section-body">
            <!-- 按接口顺序循环 -->
            <div
              v-for="(field, idx) in visibleFields"
              :key="
                (field.name || 'field') + '-' + (field.sort || '') + '-' + idx
              "
              class="form-item"
            >
              <!-- 咨询类型（保持不变） -->
              <template v-if="field.name === 'consulttype'">
                <label class="required">咨询类型</label>
                <input type="text" v-model="consultTypeLabel" readonly />
              </template>

              <!-- 预约时间 -->
              <template v-else-if="field.name === 'bookingTime'">
                <label class="required">预约时间</label>
                <input type="text" v-model="formData.plantime" readonly />
              </template>

              <!-- 主题一级 -->
              <template v-else-if="field.name === 'themelevel1'">
                <label class="required">请选择你想咨询的主题</label>
                <select
                  v-model="formData.themelevel1"
                  @change="onTopic1Change"
                  required
                >
                  <option value="" disabled>请选择主题</option>
                  <option
                    v-for="(t, tIdx) in topics"
                    :key="(t.id || t.displayName) + '-' + tIdx"
                    :value="t.displayName"
                  >
                    {{ t.displayName }}
                  </option>
                </select>
              </template>

              <!-- 主题二级 -->
              <template v-else-if="field.name === 'themelevel2'">
                <label class="required">二级主题</label>
                <select v-model="formData.themelevel2" required>
                  <option value="" disabled>请选择子主题</option>
                  <option
                    v-for="(sub, sIdx) in topic2Options"
                    :key="sub + '-' + sIdx"
                    :value="sub"
                  >
                    {{ sub }}
                  </option>
                </select>
              </template>

              <!-- 国家地区选择器 -->
              <template v-else-if="field.name === 'city'">
                <label>所在地区</label>
                <div class="location-selector">
                  <select v-model="selectedCountry" @change="onCountryChange">
                    <option value="">请选择国家</option>
                    <option
                      v-for="(country, index) in countries"
                      :key="generateKey(country.id, country.title, index)"
                      :value="country.id"
                    >
                      {{ country.title }}
                    </option>
                  </select>

                  <select
                    v-model="selectedProvince"
                    @change="onProvinceChange"
                    :disabled="!hasProvinces"
                  >
                    <option value="">请选择省份/州</option>
                    <option
                      v-for="(province, index) in provinces"
                      :key="generateKey(province.id, province.title, index)"
                      :value="province.id"
                    >
                      {{ province.title }}
                    </option>
                  </select>

                  <select
                    v-model="selectedCity"
                    @change="onCityChange"
                    :disabled="!hasCities"
                  >
                    <option value="">请选择城市</option>
                    <option
                      v-for="(city, index) in cities"
                      :key="generateKey(city.id, city.title, index)"
                      :value="city.id"
                    >
                      {{ city.title }}
                    </option>
                  </select>

                  <select
                    v-model="selectedDistrict"
                    @change="onDistrictChange"
                    :disabled="!hasDistricts"
                  >
                    <option value="">请选择区县</option>
                    <option
                      v-for="(district, index) in districts"
                      :key="generateKey(district.id, district.title, index)"
                      :value="district.id"
                    >
                      {{ district.title }}
                    </option>
                  </select>
                </div>
                <!-- 显示选中的地区 -->
                <div v-if="selectedAreaText" class="selected-area">
                  已选择: {{ selectedAreaText }}
                </div>
              </template>

              <!-- 通用渲染 -->
              <template v-else>
                <label v-if="field.label" :class="{ required: field.required }">
                  {{ field.label }}
                </label>

                <input
                  v-if="field.type === 'input'"
                  type="text"
                  v-model="formData[field.name]"
                  :readonly="field.readonly"
                  :placeholder="field.placeholder || ''"
                  :required="field.required"
                />

                <select
                  v-else-if="field.type === 'select'"
                  v-model="formData[field.name]"
                  :disabled="field.readonly"
                  :required="field.required"
                >
                  <option
                    v-for="(opt, oIdx) in field.options || []"
                    :key="(opt.value || opt.label) + '-' + oIdx"
                    :value="opt.value"
                    :disabled="opt.disabled"
                  >
                    {{ opt.label }}
                  </option>
                </select>

                <div v-else-if="field.type === 'radio'" class="radio-group">
                  <label
                    v-for="(radio, rIdx) in field.radios || []"
                    :key="(radio.value || radio.label) + '-' + rIdx"
                    class="radio-option"
                  >
                    <input
                      type="radio"
                      :name="field.name"
                      :value="radio.value"
                      v-model="formData[field.name]"
                      :disabled="field.readonly"
                    />
                    <span class="radio-label">{{ radio.label }}</span>
                  </label>
                </div>

                <textarea
                  v-else-if="field.type === 'textarea'"
                  v-model="formData[field.name]"
                  :readonly="field.readonly"
                  :placeholder="field.placeholder || ''"
                  :required="field.required"
                ></textarea>

                <input
                  v-else-if="field.type === 'file'"
                  type="file"
                  @change="handleFileUpload($event, field.name)"
                  :disabled="field.readonly"
                />
              </template>
            </div>
          </div>
        </div>

        <!-- 提交按钮 -->
        <div class="form-section">
          <div class="section-body">
            <div class="form-item">
              <button
                type="submit"
                class="submit-button"
                :disabled="submitting"
              >
                {{ submitting ? "提交中..." : "提交" }}
              </button>
            </div>
          </div>
        </div>
      </form>
    </div>

    <!-- 自定义轻提示 -->
    <div v-if="showToast" class="custom-toast" :class="toastType">
      <div class="toast-content">
        <span class="toast-icon">{{ toastIcon }}</span>
        <span class="toast-message">{{ toastMessage }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import { toReserve, topics, reserve, tree } from "@/api/user";

export default {
  name: "AppointmentForm",
  data() {
    return {
      fields: [],
      formData: {
        consulttype: "",
        plantime: "",
        themelevel1: "",
        themelevel2: "",
        city: "", // 城市字段，只存储最后一级
      },
      consultTypeLabel: "",
      topics: [],
      topic2Options: [],
      // 国家地区选择器相关数据
      cityData: [],
      countries: [],
      provinces: [],
      cities: [],
      districts: [],
      selectedCountry: "",
      selectedProvince: "",
      selectedCity: "",
      selectedDistrict: "",
      // 提示相关
      showToast: false,
      toastMessage: "",
      toastType: "success", // success, error, warning
      toastTimer: null,
      submitting: false,
    };
  },
  computed: {
    visibleFields() {
      return this.fields.filter((f) => f.hide === false);
    },
    // 选中的地区完整路径文本（用于显示）
    selectedAreaText() {
      if (!this.selectedCountry) return "";

      const country = this.countries.find((c) => c.id === this.selectedCountry);
      if (!country) return "";

      let text = country.title;

      if (this.selectedProvince) {
        const province = this.provinces.find(
          (p) => p.id === this.selectedProvince
        );
        if (province) {
          text += ` / ${province.title}`;
        }
      }

      if (this.selectedCity) {
        const city = this.cities.find((c) => c.id === this.selectedCity);
        if (city) {
          text += ` / ${city.title}`;
        }
      }

      if (this.selectedDistrict) {
        const district = this.districts.find(
          (d) => d.id === this.selectedDistrict
        );
        if (district) {
          text += ` / ${district.title}`;
        }
      }

      return text;
    },
    // 提示图标
    toastIcon() {
      switch (this.toastType) {
        case "success":
          return "✓";
        case "error":
          return "✕";
        case "warning":
          return "!";
        default:
          return "✓";
      }
    },
    // 是否有省份数据
    hasProvinces() {
      return this.selectedCountry && this.provinces.length > 0;
    },
    // 是否有城市数据
    hasCities() {
      return this.selectedProvince && this.cities.length > 0;
    },
    // 是否有区县数据
    hasDistricts() {
      return this.selectedCity && this.districts.length > 0;
    },
  },
  created() {
    this.consultantId = this.$route.query.consultantId;

    // 咨询类型映射
    const typeMap = {
      PHONE: "电话咨询",
      PVIDEO: "视频咨询",
    };
    this.formData.consulttype = this.$route.query.consulttype || "";
    this.consultTypeLabel = typeMap[this.formData.consulttype] || "";

    // 预约时间
    this.formData.plantime = this.formatTime(this.$route.query.plantime || "");

    this.gettoReserve();
    this.getConsultantTopics();
    this.gettree(); // 获取城市数据
  },
  methods: {
    // 生成唯一key，解决重复ID问题
    generateKey(id, title, index) {
      return `${id}-${title}-${index}`;
    },

    // 格式化预约时间
    formatTime(str) {
      if (!str || str.length !== 12) return str;
      const y = str.substring(0, 4);
      const m = str.substring(4, 6);
      const d = str.substring(6, 8);
      const hh = str.substring(8, 10);
      const mm = str.substring(10, 12);
      return `${y}-${m}-${d} ${hh}:${mm}`;
    },

    // 获取城市数据
    gettree() {
      tree().then((res) => {
        if (res.code === 200) {
          this.cityData = res.data || [];
          this.processCountryData();
        }
      });
    },

    // 处理国家数据，去重
    processCountryData() {
      // 使用Map来去重，基于id和title的组合
      const uniqueCountries = new Map();

      this.cityData.forEach((country) => {
        const key = `${country.id}-${country.title}`;
        if (!uniqueCountries.has(key)) {
          uniqueCountries.set(key, country);
        }
      });

      this.countries = Array.from(uniqueCountries.values());
    },

    // 国家变化
    onCountryChange() {
      this.selectedProvince = "";
      this.selectedCity = "";
      this.selectedDistrict = "";
      this.provinces = [];
      this.cities = [];
      this.districts = [];

      if (this.selectedCountry) {
        const country = this.countries.find(
          (c) => c.id === this.selectedCountry
        );
        if (country && country.children && country.children.length > 0) {
          this.provinces = country.children;
        } else {
          // 如果没有省份数据，直接使用国家名称
          this.updateCityField();
        }
      } else {
        this.formData.city = "";
      }
    },

    // 省份变化
    onProvinceChange() {
      this.selectedCity = "";
      this.selectedDistrict = "";
      this.cities = [];
      this.districts = [];

      if (this.selectedProvince) {
        const province = this.provinces.find(
          (p) => p.id === this.selectedProvince
        );
        if (province && province.children && province.children.length > 0) {
          this.cities = province.children;
        } else {
          // 如果没有城市数据，直接使用省份名称
          this.updateCityField();
        }
      } else {
        this.updateCityField();
      }
    },

    // 城市变化
    onCityChange() {
      this.selectedDistrict = "";
      this.districts = [];

      if (this.selectedCity) {
        const city = this.cities.find((c) => c.id === this.selectedCity);
        if (city && city.children && city.children.length > 0) {
          this.districts = city.children;
        } else {
          // 如果没有区县数据，直接使用城市名称
          this.updateCityField();
        }
      } else {
        this.updateCityField();
      }
    },

    // 区县变化
    onDistrictChange() {
      this.updateCityField();
    },

    // 更新表单中的城市字段 - 只使用最后一级
    updateCityField() {
      // 优先使用最细粒度的级别
      if (this.selectedDistrict) {
        const district = this.districts.find(
          (d) => d.id === this.selectedDistrict
        );
        if (district) {
          this.formData.city = district.title;
          return;
        }
      }

      if (this.selectedCity) {
        const city = this.cities.find((c) => c.id === this.selectedCity);
        if (city) {
          this.formData.city = city.title;
          return;
        }
      }

      if (this.selectedProvince) {
        const province = this.provinces.find(
          (p) => p.id === this.selectedProvince
        );
        if (province) {
          this.formData.city = province.title;
          return;
        }
      }

      if (this.selectedCountry) {
        const country = this.countries.find(
          (c) => c.id === this.selectedCountry
        );
        if (country) {
          this.formData.city = country.title;
          return;
        }
      }

      this.formData.city = "";
    },

    // 显示自定义提示
    showCustomToast(message, type = "success") {
      // 清除之前的定时器
      if (this.toastTimer) {
        clearTimeout(this.toastTimer);
      }

      this.toastMessage = message;
      this.toastType = type;
      this.showToast = true;

      // 1秒后自动隐藏
      this.toastTimer = setTimeout(() => {
        this.showToast = false;
      }, 1000);
    },

    gettoReserve() {
      toReserve({
        consultantId: this.consultantId,
        userId: localStorage.getItem("userId"),
        unitId: localStorage.getItem("unitId"),
      }).then((res) => {
        if (res.code === 200) {
          this.fields = res.data || [];
          // 初始化 formData
          this.fields.forEach((f) => {
            this.$set(this.formData, f.name, f.value || "");
          });
        }
      });
    },

    getConsultantTopics() {
      topics({ unitId: localStorage.getItem("unitId") }).then((res) => {
        if (res.code === 200) {
          this.topics = res.data || [];
        }
      });
    },

    onTopic1Change() {
      const selected = this.topics.find(
        (t) => t.displayName === this.formData.themelevel1
      );
      this.topic2Options = selected ? selected.subTopics || [] : [];
      this.formData.themelevel2 = "";
    },

    handleFileUpload(e, name) {
      const file = e.target.files[0];
      this.formData[name] = file;
    },

    goBack() {
      this.$router.go(-1);
    },

    // 构建提交 payload
    buildPayload() {
      const typeReverseMap = {
        电话咨询: "PHONE",
        视频咨询: "PVIDEO",
      };
      const consulttype =
        this.formData.consulttype ||
        typeReverseMap[this.consultTypeLabel] ||
        "";

      const payload = {
        age: this.formData.age,
        bookingTime: this.formatBookingTime(this.$route.query.plantime),
        city: this.formData.city, // 只包含最后一级的地区名称
        clientname: this.formData.clientname,
        clienttype: this.formData.clienttype,
        consultantid: Number(this.$route.query.consultantId),
        consulttype,
        gender: this.formData.gender,
        name: this.formData.name,
        phone: this.formData.phone,
        themelevel1: this.formData.themelevel1,
        themelevel2: this.formData.themelevel2,
        userId: Number(localStorage.getItem("userId")),
      };

      // 可选参数
      const optional = [
        "changType",
        "companyno",
        "department",
        "email",
        "emergencyContact",
        "emergencyPhone",
        "location",
        "memberno",
        "message",
        "moreinfo1",
        "moreinfo2",
        "moreinfo3",
        "name",
        "otherway",
        "oversea",
        "prop1",
        "prop2",
        "qq",
        "subcompany",
        "unitname",
        "username",
        "way",
        "wos1",
        "wos2",
        "wos3",
        "wos4",
        "wos5",
        "wx",
        "zxType",
      ];
      optional.forEach((k) => {
        if (this.formData[k]) payload[k] = this.formData[k];
      });

      return payload;
    },

    // 格式化预约时间为接口要求格式
    formatBookingTime(str) {
      if (!str || str.length !== 12) return str;
      const y = str.substring(0, 4);
      const m = str.substring(4, 6);
      const d = str.substring(6, 8);
      const hh = str.substring(8, 10);
      const mm = str.substring(10, 12);
      const start = `${hh}:${mm}`;
      const end = `${String(Number(hh) + 1).padStart(2, "0")}:${mm}`;
      return `${y}${m}${d} ${start}-${end}`;
    },

    submitForm() {
      this.submitting = true;

      const payload = this.buildPayload();

      let submitData = payload;
      if (this.formData.moreinfo4 instanceof File) {
        const fd = new FormData();
        Object.keys(payload).forEach((k) => {
          fd.append(k, payload[k]);
        });
        fd.append("moreinfo4", this.formData.moreinfo4);
        submitData = fd;
      }

      reserve(submitData)
        .then((res) => {
          this.submitting = false;

          if (res.code === 200) {
            // 显示成功提示
            this.showCustomToast("提交成功！", "success");

            // 1秒后返回主页
            setTimeout(() => {
              this.$router.push({ name: "员工端-首页" });
            }, 2000);
          } else {
            // 错误提示
            this.showCustomToast(res.message || "提交失败，请重试", "error");
          }
        })
        .catch((error) => {
          this.submitting = false;
          this.showCustomToast("网络错误，请重试", "error");
        });
    },
  },
};
</script>

<style scoped>
/* 之前的样式保持不变，只添加新的样式 */

.appointment-form {
  max-width: 500px;
  margin: 0 auto;
  font-family: "PingFang SC", "Helvetica Neue", Arial, sans-serif;
  background-color: #f5f5f5;
  min-height: 100vh;
  position: relative;
}

.page-header {
  background-color: #fff;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 10;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.back-button {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  padding: 5px;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  color: #333;
}

.placeholder {
  width: 40px;
}

.form-container {
  padding: 20px;
}

.form-section {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  overflow: hidden;
}

.section-header {
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.section-title {
  display: flex;
  align-items: center;
}

.title-decoration {
  width: 3px;
  height: 20px;
  background: linear-gradient(to bottom, #b3d2fa, #678fcd);
  margin-right: 10px;
}

.title-text {
  font-weight: 600;
  font-size: 16px;
}

.section-body {
  padding: 15px;
}

.form-item {
  margin-bottom: 20px;
}

.form-item:last-child {
  margin-bottom: 0;
}

label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
}

label.required::after {
  content: "*";
  color: #f56c6c;
  margin-left: 4px;
}

input,
select {
  width: 100%;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

input:read-only,
select:disabled {
  background-color: #f5f7fa;
  color: #909399;
  cursor: not-allowed;
}

.radio-group {
  display: flex;
}

.radio-option {
  display: flex;
  align-items: center;
  margin-right: 20px;
}

.radio-option input {
  width: auto;
  margin-right: 5px;
}

.theme-container {
  display: flex;
  gap: 10px;
}

.theme-container input {
  flex: 1;
}

/* 国家地区选择器样式 */
.location-selector {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 10px;
}

.location-selector select {
  width: 100%;
}

.selected-area {
  padding: 8px 12px;
  background-color: #f0f9ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
  color: #1890ff;
  font-size: 14px;
}

.final-selection {
  margin-top: 5px;
  padding: 4px 8px;
  background-color: #e6f7ff;
  border-radius: 4px;
  font-size: 12px;
  color: #0050b3;
}

.submit-button {
  width: 100%;
  padding: 12px;
  background-color: #1e74fd;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-button:hover:not(:disabled) {
  background-color: #0d66e8;
}

.submit-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* 自定义轻提示样式 */
.custom-toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 9999;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  animation: toastSlideIn 0.3s ease-out;
  min-width: 200px;
  text-align: center;
}

.custom-toast.success {
  background-color: #f6ffed;
  border: 1px solid #b7eb8f;
  color: #52c41a;
}

.custom-toast.error {
  background-color: #fff2f0;
  border: 1px solid #ffccc7;
  color: #ff4d4f;
}

.custom-toast.warning {
  background-color: #fffbe6;
  border: 1px solid #ffe58f;
  color: #faad14;
}

.toast-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.toast-icon {
  font-weight: bold;
  font-size: 16px;
}

.toast-message {
  font-size: 14px;
  font-weight: 500;
}

@keyframes toastSlideIn {
  from {
    opacity: 0;
    transform: translate(-50%, -60%);
  }
  to {
    opacity: 1;
    transform: translate(-50%, -50%);
  }
}

/* 响应式设计 */
@media (min-width: 768px) {
  .location-selector {
    flex-direction: row;
  }

  .location-selector select {
    flex: 1;
  }
}
</style>
